package com.JumpAndJump.service.impl;

import com.JumpAndJump.common.ServerResponse;
import com.JumpAndJump.dao.UserMapper;
import com.JumpAndJump.pojo.User;
import com.JumpAndJump.service.IScoreService;
import com.JumpAndJump.vo.Score;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by Administrator on 2018/1/7.
 */
@Service("iScoreService")
public class ScoreServiceImpl implements IScoreService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public ServerResponse<Score> getScore(int ID) {
        User user = userMapper.selectByPrimaryKey(ID);
        if (user == null)
            return ServerResponse.createByErrorMessage("系统异常");
        return ServerResponse.createBySuccess("获取成功", new Score(user.getUerid(), user.getUsername(), user.getScoremax()));
    }

    @Override
    public ServerResponse<Score> updateScore(int ID, int score) {
        User user = userMapper.selectByPrimaryKey(ID);
        if (user == null)
            return ServerResponse.createByErrorMessage("系统异常");
        int count = userMapper.updateScoreByID(ID, score);
        if (count < 0) {
            return ServerResponse.createByErrorMessage("系统异常");
        }
        return ServerResponse.createBySuccessMessage("修改成功");
    }

    @Override
    public ServerResponse<PageInfo> getScoreList(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> userList = userMapper.getscoreList();
        List<Score> scoreList = Lists.newArrayList();
        for (User user : userList) {
            Score score = this.createScoreByUser(user);
            scoreList.add(score);
        }
        PageInfo pageResult = new PageInfo(userList);
        pageResult.setList(scoreList);
        return ServerResponse.createBySuccess(pageResult);

    }

    public Score createScoreByUser(User user) {
        Score score = new Score();
        score.setUserID(user.getUerid());
        score.setUsername(user.getUsername());
        score.setScore(user.getScoremax());
        return score;
    }

    @Override
    public ServerResponse<Score> getPersonList(int ID) {
        User user = userMapper.selectByPrimaryKey(ID);
        int i = 1;
        if (user == null)
            return ServerResponse.createByErrorMessage("系统异常:未找到该ID");
        List<User> userList = userMapper.getscoreList();
        for (User userItem : userList) {
            if (userItem.getUerid() == ID)
                return ServerResponse.createBySuccessMessage(String.valueOf(i));
            i++;
        }
        return ServerResponse.createByErrorMessage("系统异常:未找到该ID排名");
    }
}
